/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.common.configuration;

import com.inspur.edp.lcm.metadata.api.entity.MetadataType;
import com.inspur.edp.lcm.metadata.common.ServiceUtils;
import io.iec.edp.caf.boot.context.CAFContext;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 元数据类型配置加载器
 *
 * @author zhongchq
 * @since 1.0
 */
public class MetadataTypeConfigLoader {

    private static final String FILE_NAME = "config/platform/common/lcm_metadataextend.json";
    private static final String SECTION_NAME = "MetadataType";
    private List<MetadataType> metadataTypeList;
    private Map<String, List<MetadataType>> metadataTypeMap;

    public Map<String, List<MetadataType>> getMetadataTypeMap() {
        if (metadataTypeMap == null) {
            metadataTypeMap = new HashMap<>();
        }
        return metadataTypeMap;
    }

    private String absoluteFilePath;

    public String getAbsoluteFilePath() {
        if (StringUtils.isEmpty(absoluteFilePath)) {
            absoluteFilePath = ServiceUtils.getAbsoluteConfigFilePath(FILE_NAME);
        }
        return absoluteFilePath;
    }

    /**
     * 类初始化时反序列化Json到实体
     *
     * @return java.util.List<com.inspur.gsp.lcm.metadata.entity.MetadataType>
     * @author zhongchq
     **/
    public List<MetadataType> loadMetadataConfigurations() {
        String language = CAFContext.current.getLanguage();
        try {
            if (!getMetadataTypeMap().containsKey(language)) {
                metadataTypeList = MetadataServiceHelper.getConfigurationList(getAbsoluteFilePath(), SECTION_NAME, MetadataType.class);
                getMetadataTypeMap().put(language, metadataTypeList);
            }
            return getMetadataTypeMap().get(language);
        } catch (IOException e) {
            throw new RuntimeException("读取配置文件失败：" + getAbsoluteFilePath(), e);
        }
    }
}
